package com.jeesite.modules.yzw.service;

import com.alibaba.fastjson.JSONObject;
import com.jeesite.modules.yzw.constant.Constant;
import com.jeesite.modules.yzw.config.YzwProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;


/**
 * 易政网接口
 * @author guohusong
 * @version 1.0
 * @date 2022/4/30 10:30
 */
@Component
public class YzwClient {
    private static final Logger logger = LoggerFactory.getLogger(YzwClient.class);
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private YzwProperties yzwProperties;

    /**
     * 使用RestTemplate调用接口获取返回的数据
     * @param url
     * @param postParameters (MultiValueMap<String, String>)
     * @return
     */
    public String getResponse(String url, MultiValueMap<String, String> postParameters) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", Constant.CONTENT_TYPE);
        headers.add("Accept", MediaType.TEXT_PLAIN_VALUE);
        postParameters.add("version", Constant.YZW_VERSION);
        HttpEntity<MultiValueMap<String, String>> r = new HttpEntity<>(postParameters, headers);
        return restTemplate.postForObject(url, r, String.class);
    }

    /**
     * 获取token信息(调用成功返回token值，或者返回null)
     * @param currentUserId 登录用户id
     * @return
     */
    public String getLxToken(String currentUserId) {
        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("currentUserId", currentUserId);
        String response = getResponse(getUrl(yzwProperties.getYzwDevurl(), Constant.CallPath.GET_TOKEN), postParameters);
        logger.info("form表单模拟数据为："+ com.alibaba.fastjson.JSON.toJSONString(postParameters));
        logger.info(response);

        //获取token参数
        if(!StringUtils.isEmpty(response)) {
            JSONObject resultObj = (JSONObject) JSONObject.parse(response);
            if(resultObj.get(Constant.ResultCode.RCODE_RESULT_CODE).equals(Constant.ResultCode.RCODE_SUCCESS)) { //校验调用是否成功
                String result = resultObj.getString(Constant.ResultCode.RCODE_RESULT);
                JSONObject tokenObj = (JSONObject) JSONObject.parse(result);
                return tokenObj.getString(Constant.ResultCode.RCODE_RESULT_TOKEN);
            }
        }
        return null;
    }
    /**
     * 单点登陆验证
     * @param currentUserId 登录用户id
     * @param token
     */
    public String checkLxLogin(String currentUserId, String token) {
        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("currentUserId", currentUserId);
        postParameters.add("args", String.format("{\"token\":\"%s\"}", token));
        return getResponse(getUrl(yzwProperties.getYzwDevurl(), Constant.CallPath.CHECK_LOGIN), postParameters);
    }
    public JSONObject checkLxLoginObj(String currentUserId, String token){
       return getResultObj(checkLxLogin(currentUserId, token));
    }
    public JSONObject getResultObj(String response) {
        if(!StringUtils.isEmpty(response)) {
            JSONObject resultObj = (JSONObject) JSONObject.parse(response);
            if(resultObj.get(Constant.ResultCode.RCODE_RESULT_CODE).equals(Constant.ResultCode.RCODE_SUCCESS)) { //校验调用是否成功
                //返回结果正文数据
                return resultObj.getJSONObject(Constant.ResultCode.RCODE_RESULT);
            }
        }
        return null;
    }
    /**
     * 用户信息查询接口(全量)
     * @param currentUserId 登录用户id
     */
    public String queryUserList(String currentUserId) {
        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("currentUserId", currentUserId);
        postParameters.add("args", "{}");

        String response = getResponse(getUrl(yzwProperties.getYzwDevurl(), Constant.CallPath.QUERY_USER), postParameters);
        logger.info(response);
        return getResult(response);
    }
    /**
     * 用户信息查询接口(按日期)
     * @param startDate
     * @param endDate
     * @param currentUserId 登录用户id
     */
    public String queryUserListByDate(String startDate, String endDate, String currentUserId) {
        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("currentUserId", currentUserId);
        postParameters.add("args", String.format("{\"startDate\":\"%s\",\"endDate\":\"%s\"}", startDate, endDate));

        String response = getResponse(getUrl(yzwProperties.getYzwDevurl(), Constant.CallPath.QUERY_USER), postParameters);
        logger.info(response);
        return getResult(response);
    }
    /**
     * 组织机构查询
     * @param currentUserId 登录用户id
     * @return
     */
    public String queryDeptList(String currentUserId) {
        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("currentUserId", currentUserId);
        postParameters.add("args", "{}");

        logger.info("form表单模拟数据为："+ com.alibaba.fastjson.JSON.toJSONString(postParameters));
        String response = getResponse(getUrl(yzwProperties.getYzwDevurl(), Constant.CallPath.QUERY_DEPT_LIST), postParameters);
        logger.info(response);
        return getResult(response);
    }

    /**
     * 根据日期查询组织机构信息
     * @param startDate
     * @param endDate
     * @param currentUserId
     * @return
     */
    public String queryDeptListByDate(String startDate, String endDate, String currentUserId) {
        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("currentUserId", currentUserId);
        postParameters.add("args", String.format("{startDate:\"%s\",endDate:\"%s\"}", startDate, endDate));
        String response = getResponse(getUrl(yzwProperties.getYzwDevurl(), Constant.CallPath.QUERY_DEPT_LIST), postParameters);
        logger.info(response);
        return getResult(response);
    }
    /**
     * 组织机构用户查询
     * @param currentUserId 登录用户id
     * @return
     */
    public String queryDeptUserList(String currentUserId) {
        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("currentUserId", currentUserId);
        postParameters.add("args", "{}");

        String response = getResponse(getUrl(yzwProperties.getYzwDevurl(), Constant.CallPath.QUERY_DEPT_USER_LIST), postParameters);
        return getResult(response);
    }
    /**
     * 组织机构用户查询
     * @param currentUserId 登录用户id
     * @return
     */
    public String queryDeptUserListByDate(String startDate, String endDate,String currentUserId) {
        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("currentUserId", currentUserId);
        postParameters.add("args", String.format("{startDate:\"%s\",endDate:\"%s\"}", startDate, endDate));

        String response = getResponse(getUrl(yzwProperties.getYzwDevurl(), Constant.CallPath.QUERY_DEPT_USER_LIST), postParameters);
        return getResult(response);
    }
    /**
     * 通过用户信息查询用户所在组织
     * @param userName
     * @param currentUserId
     * @return
     */
    public String queryDeptUserListByUserName(String userName,String currentUserId) {
        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("currentUserId", currentUserId);
        postParameters.add("args", String.format("{userName:\"%s\"}", userName));

        String response = getResponse(getUrl(yzwProperties.getYzwDevurl(), Constant.CallPath.QUERY_DEPT_USER_LIST), postParameters);
        return getResult(response);
    }
    /**
     * 消息推送
     * @param userId 消息接收人id
     * @param type 消息类型
     * @param content 消息内容(json格式字符串)
     * @param currentUserId 登录用户id
     * @return
     */
    public String pushMsg(String userId, String type, String content, String currentUserId) {
        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("currentUserId", currentUserId);
        postParameters.add("args", String.format("{userId:\"%s\",type:\"%s\",content:%s}", userId, type, content));

        String response = getResponse(getUrl(yzwProperties.getYzwDevurl(), Constant.CallPath.PUSH_MSG), postParameters);
        return getResult(response);
    }
    /**
     * 发送消息
     * @param content
     * @param currentUserId
     * @return
     */
    public String pushMessage(String content, String currentUserId) {
        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("currentUserId", currentUserId);
        postParameters.add("args",  content);
        logger.info(String.format("易政网消息发送请求数据：【%s】",com.alibaba.fastjson.JSON.toJSONString(postParameters)));

        String response = getResponse(getUrl(yzwProperties.getYzwDevurl(), Constant.CallPath.PUSH_MSG), postParameters);
        logger.info(String.format("易政网消息发送返回数据：【%s】",response));
        return getResult(response);
    }

    /**
     * 待办变动提醒
     * @param currentUserId
     * @param subjectUserId
     * @return
     */
    public String sendLxWebMessage(String currentUserId, String subjectUserId) {
        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("currentUserId", currentUserId);
        postParameters.add("args", String.format("{userId:\"%s\",content:\"%s\"}", subjectUserId, Constant.MsgType.LH_ZHDC));

        logger.info(String.format("易政网待办变动提醒数据：【%s】", com.alibaba.fastjson.JSON.toJSONString(postParameters)));

        String response = getResponse(getUrl(yzwProperties.getYzwDevurl(), Constant.CallPath.SEND_WEB_MSG), postParameters);
        logger.info(String.format("易政网待办变动提醒数据：【%s】", response));
        return getResult(response);
    }

    /**
     * 拼接URL地址
     * @param prefix
     * @param suffix
     * @return
     */
    public String getUrl(String prefix, String suffix) {
        StringBuffer sb = new StringBuffer();
        return sb.append(prefix).append(suffix).toString();
    }

    /**
     * 接口调用成功后，获取结果正文
     * @param response
     * @return
     */
    public String getResult(String response) {
        if(!StringUtils.isEmpty(response)) {
            JSONObject resultObj = (JSONObject) JSONObject.parse(response);
            if(resultObj.get(Constant.ResultCode.RCODE_RESULT_CODE).equals(Constant.ResultCode.RCODE_SUCCESS)) { //校验调用是否成功
                //返回结果正文数据
                return resultObj.getString(Constant.ResultCode.RCODE_RESULT);
            }
        }
        return null;
    }
    /**
     * 获取json的数据
     * @param token
     * @return
     */
    public String getMobile(String token) {
        //获取用户信息
        String userinfoJson = checkLxLogin(Constant.TestData.CURRENT_USER_ID, token);
        //获取手机号
        String json = getResult(userinfoJson);
        if(!StringUtils.isEmpty(json)) {
            JSONObject obj = (JSONObject) JSONObject.parse(json);
            return obj.getString("mobilePhone");
        }
        return null;
    }
}
